package com.chat.business;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.chat.data.LoginInfoItem;
import com.chat.data.UserInfoBaseItem;
import com.chat.data.UserInfoDetItem;
import com.chat.util.ChatConstants;
import com.uday.frmwrk.data.BaseRequestItem;
import com.uday.frmwrk.data.BaseResponseItem;
import com.uday.frmwrk.service.FlexSessionActivity;

import flex.messaging.MessageBroker;
import flex.messaging.MessageDestination;
import flex.messaging.services.MessageService;

public class LoginActivity extends FlexSessionActivity {
	public static List<UserInfoBaseItem> lstUserBaseInfo = new ArrayList<UserInfoBaseItem>();
	public static List<UserInfoDetItem> lstUserDetInfo = new ArrayList<UserInfoDetItem>();
	public static FriendListServiceImpl objFriendListServiceImpl = new FriendListServiceImpl();
	public static InactiveUserCleanupThread objCleanupThread = new InactiveUserCleanupThread();
	public static Map<Long, String> mapUserIDQue = new HashMap<Long, String>();
	
	private static Long lngCurrSeqID = 100l;

	public LoginActivity() {
		objFriendListServiceImpl.start();
		//objCleanupThread.start();
	}

	public boolean process(BaseRequestItem objBaseRequestItem,
			BaseResponseItem objBaseResponseItem) throws Exception {
		LoginInfoItem objLoginInfoItem = (LoginInfoItem) objBaseRequestItem
				.getObjReqData();

		List<UserInfoDetItem> lstUsers = getSqlMapClientTemplate()
				.queryForList("getUserDetails", objLoginInfoItem);
		if (lstUsers.size() == 1) {
			UserInfoDetItem objUserInfoItem = lstUsers.get(0);

			getSqlMapClientTemplate().update("updateDtLastAccessed",
					objUserInfoItem);

			MessageBroker broker = MessageBroker.getMessageBroker(null);
			MessageService service = (MessageService) broker
					.getService(ChatConstants.MESSAGE_SERVICE);
			
			//Setting a random id which will identify this user for this session
			objUserInfoItem.setLngUserID(objUserInfoItem.getLngDBUserID());

			String strMsgQueNm = objLoginInfoItem.getStrIdLogin()
					+ objLoginInfoItem.getStrPassword().replaceAll("=", "");
			strMsgQueNm += (lngCurrSeqID++).toString();

		    LogoutActivity.logoutUser(objUserInfoItem);

			lstUserBaseInfo.add(objUserInfoItem.getUserInfoBaseItem());
			lstUserDetInfo.add(objUserInfoItem);
            MessageDestination destination = (MessageDestination) service
            .createDestination(strMsgQueNm);

            if (service.isStarted()) {
                destination.start();
            } else {
                service.start();
                destination.start();
            }
            
            objUserInfoItem.setStrMsgQueueID(strMsgQueNm);

			mapUserIDQue.put(objUserInfoItem.getLngUserID(), strMsgQueNm);
			ArrayList<UserInfoBaseItem> arrFriendList = new ArrayList<UserInfoBaseItem>(lstUserBaseInfo);
			arrFriendList.remove(objUserInfoItem.getUserInfoBaseItem());

			objBaseResponseItem.getLstDataItems().add(objUserInfoItem);
			objBaseResponseItem.getLstDataItems().add(arrFriendList);
			
			FriendListServiceImpl.blnRefreshList = true;
			System.out.println("Login in user ID:" + objUserInfoItem.getLngUserID());
	        System.out.println("Count of users currently online " + lstUserDetInfo.size());

			return true;

		} else {
			List<String> lstErrors = new ArrayList<String>();
			lstErrors.add("Invalid Login ID/Password");
			objBaseResponseItem.setLstErrorList(lstErrors);
			return false;
		}
	}
	
	private int getUniqueRandomUserID(){
        Random objRandom = new Random();
        objRandom.setSeed(new Date().getTime());
        
        int intRandUID = Math.abs(objRandom.nextInt());

        synchronized (mapUserIDQue) {
            while(mapUserIDQue.containsKey(lngCurrSeqID.toString())){
                intRandUID = Math.abs(objRandom.nextInt());
            }
        }
	    return intRandUID;
	}

}
